package com.javaweb.service.impl;

import com.javaweb.entity.User;
import com.javaweb.mapper.RoomMapper;
import com.javaweb.entity.Room;
import com.javaweb.mapper.UserMapper;
import com.javaweb.service.RoomService;
import com.javaweb.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;

@Service
public class RoomServiceImpl implements RoomService {

    @Autowired
    private RoomMapper roomMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public void add(Room room) {
        //补充属性值
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        room.setCreatorId(userId);

        roomMapper.add(room);
    }

    @Override
    public List<Room> listAll() {
        List<Room> rooms = roomMapper.listAll();
        for (Room room : rooms) {
            User u = userMapper.findById(room.getCreatorId());
            room.setCreatorName(StringUtils.hasLength(u.getNickname()) ? u.getNickname() : u.getUsername());
        }
        return rooms;
    }

    @Override
    public List<Room> listMine() {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        return roomMapper.listByUserId(userId);
    }

    @Override
    public Room findById(Integer id) {
        return roomMapper.findById(id);
    }

    @Override
    public void update(Room room) {
        roomMapper.update(room);
    }

    @Override
    public Room findByRoomName(String roomName) {
        return roomMapper.findByRoomName(roomName);
    }
}
